package cn.edu.ecut.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import cn.edu.ecut.util.DatabaseType;
import cn.edu.ecut.util.JdbcHelper;
import cn.edu.ecut.util.RowMapper;

public class EmployeeServlet implements Servlet {
	
	@Override
	public void init(ServletConfig config) throws ServletException {
	}

	@Override
	public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
		// 使用 JdbcHelper 工具类查询数据库中的 emp表中指定员工的 工号、姓名、部门号、部门名称
		JdbcHelper h = JdbcHelper.getInstance( DatabaseType.ORACLE );
		String sql = "SELECT e.empno , e.ename , d.deptno , d.dname " +
				     "FROM emp e JOIN dept d ON e.deptno = d.deptno WHERE e.empno = ? " ;
		RowMapper< Map<String,Object> > rowMapper = new RowMapper<>() {
			@Override
			public Map<String,Object> wrap(ResultSet rs) throws SQLException {
				Map<String, Object> map = new HashMap<>();
				map.put( "empno" , rs.getInt( "empno" ) );
				map.put( "ename" , rs.getString( "ename" ) );
				map.put( "deptno" , rs.getInt( "deptno" ) );
				map.put( "dname" , rs.getString( "dname" ) );
				return map;
			}
		} ;
		Map<String,Object> map = h.query( sql , rowMapper, 7369 );
		h.release();
		
		// 获得可以向 客户端 (浏览器) 输出数据的字符流 (打印流) 【这个说法是不合适的，暂时先这么理解着】
		PrintWriter out = res.getWriter();
		// 将 map 集合中的数据输出到 页面 上
		Set<String> keys = map.keySet();
		for( String key : keys ) {
			Object value = map.get( key );
			out.println( "<div style='border:1px solid blue ; text-align:center ; line-height : 30px '>" );
			out.println( key + " : " + value );
			out.println( "</div>" );
		}
		
	}


	@Override
	public void destroy() {
	}

	@Override
	public ServletConfig getServletConfig() {
		return null;
	}

	@Override
	public String getServletInfo() {
		return null;
	}

}
